#define WATER_THRED 200
#define BUTTON_THRED 200
#define PLAN_MOTOR_RUNTIME_AFTER_RESET_BUTTON 1700

int IN_PIN_Button = A1;
int IN_PIN_WaterLevelSenso = A4;
int OUT_PIN_Motor = 7;

unsigned long latest_button_pressed_time = 0;
unsigned long latest_water_changedTo_not_much_time = 0;
unsigned long latest_time = 0;
bool water_too_much = false;
bool shallMotorRun_ForWater = false;
bool shallMotorRun_ForResetButtonPressed = false;
bool shallMotorRun_toPressButton = false;
// int planMotorRuntime = 0;

void setup()
{
    Serial.begin(115200);
    pinMode(IN_PIN_Button, INPUT);
    pinMode(IN_PIN_WaterLevelSenso, INPUT);
    pinMode(OUT_PIN_Motor, OUTPUT);

    latest_button_pressed_time = 0;
    latest_water_changedTo_not_much_time = 0;
    latest_time = 0;
    water_too_much = false;
    shallMotorRun_ForWater = false;
    shallMotorRun_ForResetButtonPressed = false;
    shallMotorRun_toPressButton = false;

    analogRead(IN_PIN_WaterLevelSenso);
    analogRead(IN_PIN_Button);
}

void loop()
{
    //Water Level Sensor
    int inValue_WaterLevelSenso = analogRead(IN_PIN_WaterLevelSenso);
    bool tmp_water_too_much = inValue_WaterLevelSenso > WATER_THRED;
    if (!tmp_water_too_much)
    {
        if (water_too_much)
        {
            latest_water_changedTo_not_much_time = millis();
        }
    }
    water_too_much = tmp_water_too_much;

    //Reset Button
    int inValue_Button = analogRead(IN_PIN_Button);
    bool isPressed_Button = inValue_Button > BUTTON_THRED;

    if (isPressed_Button)
    {
        latest_button_pressed_time = millis();
    }

    //Checks if the motor needs run
    if (water_too_much)
    {
        shallMotorRun_ForWater = true;
    }
    else
    {
        shallMotorRun_ForWater = false;
        if (latest_water_changedTo_not_much_time > latest_button_pressed_time)
        {
            shallMotorRun_toPressButton = true;
        }
        else
        {
            shallMotorRun_toPressButton = false;
        }
    }

    latest_time = millis();
    if (latest_time - latest_button_pressed_time < PLAN_MOTOR_RUNTIME_AFTER_RESET_BUTTON)
    {
        shallMotorRun_ForResetButtonPressed = true;
    }
    else //log
    {
        if (shallMotorRun_ForResetButtonPressed)
        {
            log("From the latest button reset signal, Motor has run", latest_time - latest_button_pressed_time);
        }
        shallMotorRun_ForResetButtonPressed = false;
    }

    //Controls motor
    if (shallMotorRun_ForWater || shallMotorRun_toPressButton || shallMotorRun_ForResetButtonPressed)
    {
        digitalWrite(OUT_PIN_Motor, HIGH);
    }
    else
    {
        digitalWrite(OUT_PIN_Motor, LOW);
    }
}

void log(char *label, unsigned long value)
{
    Serial.print(label);
    Serial.print(":long:");
    Serial.println(value);
}

void log(char *label, int value)
{
    Serial.print(label);
    Serial.print(":int:");
    Serial.println(value);
}